package com.yupi.springbootinit.mq.TopicExchange;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class TopicConsumer {
    //1:定义交换机的名称
    public static final String EXCHANGE_NAME = "topic_exchange";
    public static final String A_NAME= "CQUEUE";
    public static final String B_NAME= "DQUEUE";

    public static void main(String[] args) throws IOException, TimeoutException {
        //2：创建连接工厂，指定信息
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.1.183");
        factory.setUsername("lfc");
        factory.setPassword("123456");
        //3：创建连接
        Connection connection = factory.newConnection();
        //4：创建频道
        Channel channel = connection.createChannel();
        //5：声明交换机，名称以及类型
        channel.exchangeDeclare(EXCHANGE_NAME,"topic");
        //6:创建两个队列
        channel.queueDeclare(A_NAME,false,false,false,null);
        channel.queueDeclare(B_NAME,false,false,false,null);
        //7：绑定这个队列在那个交换机上
        channel.queueBind(A_NAME,EXCHANGE_NAME,"#.后端.#");
        channel.queueBind(B_NAME,EXCHANGE_NAME,"#.前端.#");
        DeliverCallback deliverCallback1 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [员工A] Received '" + message + "'");
        };
        DeliverCallback deliverCallback2 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [员工B] Received '" + message + "'");
        };
        //8：消费消息
        channel.basicConsume(A_NAME, true, deliverCallback1, consumerTag -> { });
        channel.basicConsume(B_NAME, true, deliverCallback2, consumerTag -> { });
    }
}
